import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
// import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
import 'package:pointycastle/api.dart';
import 'package:pointycastle/block/aes_fast.dart';
import 'package:pointycastle/block/modes/cbc.dart';

class EMIBlueTool {
  ///扫描结果处理
  static List<ScanResult> didSanResult(List<ScanResult> results) {
    List<ScanResult> backDatas = [];
    for (var element in results) {
      if (element.device.advName.isNotEmpty &&
          element.device.servicesList.isNotEmpty) {
        String data1 = element.advertisementData.serviceUuids.first.str;
        String result = scanAnalysis(data1);
        // LogD(">>>>>>>>>>>>扫描结果 $result");
        if (result.contains('KRen')) backDatas.add(element);
      }
    }
    return backDatas;
  }

  ///扫描解析 获取展示设备
  static String scanAnalysis(String scanStr) {
    scanStr = scanStr.replaceAll('-', '');

    List<String> result = [];
    for (var i = 0; i < scanStr.length; i += 2) {
      result.add(scanStr.substring(i, i + 2));
    }
    List<int> bytes = result.map((hex) => int.parse(hex, radix: 16)).toList();
    String dataStr =
        bytes.map((charCode) => String.fromCharCode(charCode)).join('');
    String reversedString = dataStr.split('').reversed.join();
    return reversedString;
  }

  ///获取SN码
  static String getSNcode(ScanResult data) {
    String data1 = data.advertisementData.serviceUuids.first.str;
    String result = scanAnalysis(data1);
    String resulted = result.replaceAll('KRen', '');
    // 使用字符串切片获取后四位
    String lastFourCharacters =
        data.device.advName.substring(data.device.advName.length - 4);
    return resulted + lastFourCharacters;
  }

  ///设备数据解析
  static String deviceDataAnalysis(List<int> data) {
    return data
        .map((e) => e.toRadixString(16).padLeft(2, '0'))
        .toList()
        .join('');
  }

  static List<int> hexStringToIntList(String hex) {
    // 验证字符串长度是否是偶数
    if (hex.length % 2 != 0) {
      throw ArgumentError('Hex string must have an even number of characters');
    }

    // 初始化一个空列表存储整数
    List<int> intList = [];

    // 逐个字节地解析字符串
    for (int i = 0; i < hex.length; i += 2) {
      String byteString = hex.substring(i, i + 2);
      int byteValue = int.parse(byteString, radix: 16);
      intList.add(byteValue);
    }

    return intList;
  }

  ///数据转换
  static List<int> turnSringToListInt(String dataStr, {int? length}) {
    List<int> intList =
        length == null ? [] : List<int>.filled(length, 0, growable: false);

    for (int i = 0; i < dataStr.length; i++) {
      String hexString =
          dataStr.codeUnitAt(i).toRadixString(16).padLeft(2, '0');
      intList.add(int.parse(hexString, radix: 16));
    }
    return intList;
  }

  static List<int> turnSring16ToListInt(String dataStr) {
    List<int> intList = [];

    for (int i = 0; i < dataStr.length; i += 2) {
      if (i + 1 < dataStr.length) {
        String part = dataStr.substring(i, i + 2);
        intList.add(int.parse(part, radix: 16));
      } else {
        // 处理最后一个字符，如果字符串长度为奇数
        String part = dataStr.substring(i, i + 1);
        intList.add(int.parse(part, radix: 16));
      }
    }
    return intList.reversed.toList();
  }

  static String getCallBackKey(List<int> data) {
    if (data.length >= 4) {
      var sdata = data.sublist(0, 4);
      var ls1 = sdata.sublist(0, 1);
      var ls2 = sdata.sublist(2);
      String result = deviceDataAnalysis(ls1 + ls2);
      // result.replaceAll('fd', 'fe');
      var resulted = result.replaceAll('7e', 'aa');
      var rsed = '${resulted}blue';
      debugPrint('蓝牙回调000 ---$sdata $rsed $ls1 $ls2 $data');
      return rsed;
    }
    return '';
  }

  static String dataContent(List<int> data) {
    if (data.length > 5) {
      data.removeAt(data.length - 1);
      return deviceDataAnalysis(data.sublist(4));
    } else {
      return '';
    }
  }

  static String dataCmd(List<int> data) {
    return deviceDataAnalysis(data.sublist(3, 4));
  }
}

const String EMIKeyStr = '1234567890123456';
const String EMIIvStr = '1234567890123456';

///AES128 CBC 加密和解密
class AESHelper {
  // AES128 CBC 加密
  static Uint8List aes128CBCEncrypt(Uint8List data) {
    // ignore: deprecated_member_use
    final cipher = CBCBlockCipher(AESFastEngine());
    final params = ParametersWithIV<KeyParameter>(
      KeyParameter(
          Uint8List.fromList(EMIBlueTool.turnSringToListInt(EMIKeyStr))),
      Uint8List.fromList(EMIBlueTool.turnSringToListInt(EMIIvStr)),
    );

    cipher.init(true, params); // true表示加密

    final paddedData = padData(data); // 添加PKCS7填充
    final encrypted = cipher.process(Uint8List.fromList(paddedData));

    return encrypted;
  }

  /// AES128 CBC 解密
  static Uint8List aes128CBCDecrypt(Uint8List encryptedData) {
    // ignore: deprecated_member_use
    final cipher = CBCBlockCipher(AESFastEngine());
    final params = ParametersWithIV<KeyParameter>(
      KeyParameter(
          Uint8List.fromList(EMIBlueTool.turnSringToListInt(EMIKeyStr))),
      Uint8List.fromList(EMIBlueTool.turnSringToListInt(EMIIvStr)),
    );

    cipher.init(false, params); // false表示解密

    final decrypted = cipher.process(Uint8List.fromList(encryptedData));

    return Uint8List.fromList(decrypted); // 移除 PKCS7 填充
  }

  // PKCS7 填充
  static List<int> padData(List<int> data) {
    const blockSize = 16;
    final padLength = blockSize - (data.length % blockSize);
    final paddedData = List<int>.from(data)
      ..addAll(List<int>.filled(padLength, padLength));
    return paddedData;
  }

  // 移除 PKCS7 填充
  static List<int> removePadding(List<int> data) {
    final padLength = data.last;
    return data.sublist(0, data.length - padLength);
  }
}
